<template>
    <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto">
        <el-form-item label="标题" prop="title">
            <el-input v-model="ruleForm.title" />
        </el-form-item>
        <el-form-item label="内容" prop="content">
            <el-input type="textarea" :rows="20" v-model="ruleForm.content" />
        </el-form-item>
        <el-form-item label="接收人" prop="receiveUserIds">
            <el-select v-model="ruleForm.receiveUserIds" multiple filterable remote reserve-keyword placeholder="请输入学生名"
                :remote-method="remoteMethod" :loading="loading" style="width: 240px">
                <el-option v-for="item in options" :key="item.value" :label="item.name" :value="item.value" />
            </el-select>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="submitForm(ruleFormRef)">
                Create
            </el-button>
            <el-button @click="resetForm(ruleFormRef)">Reset</el-button>
        </el-form-item>
    </el-form>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { selectByUserName, messageSend, type ListItem } from "@/api/user"

// 选择框的加载状态
const loading = ref(false)
// 选择框的数据
const options = ref<ListItem[]>([])

// 表单数据 类型
interface RuleForm {
    title: string;
    content: string;
    receiveUserIds: number[];
}

// 获取elForm组件，后面做验证使用
const ruleFormRef = ref<FormInstance>()

// 表单数据
const ruleForm = reactive<RuleForm>({
    title: "",
    content: "",
    receiveUserIds: [],
})

// 表单验证
const rules = reactive<FormRules<RuleForm>>({
    title: [
        { required: true, message: '请输入标题', trigger: 'blur' },
    ],
    content: [
        { required: true, message: '请输入标题', trigger: 'blur' },
    ],
    receiveUserIds: [
        { validator: validatorUser, message: '请输选择接收人', trigger: 'blur' },
    ],
})

// 自定义验证接收人的函数
function validatorUser(rule: any, value: any, callback: any) {
    if (value.length > 0) {
        callback()
    } else {
        callback(new Error('请输选择接收人'))
    }
}

// 提交
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log('submit!')
            console.log(ruleForm);
            messageSend(ruleForm).then(res => {
                console.log(res);

            })
        } else {
            console.log('error submit!', fields)
        }
    })
}

// 重置表单
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

// 搜索学生
const remoteMethod = (query: string) => {
    if (query) {
        loading.value = true
        selectByUserName(query).then(res => {
            loading.value = false
            options.value = res.response as ListItem[]
        })
    } else {
        options.value = []
    }
}
</script>